package com.taichuan.keysupport.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Spinner;

import com.taichuan.keysupport.Key;

/**
 * Created by OISNY on 2016/8/19.
 */
public class KSSpinner extends Spinner {
    private static final String TAG = KSSpinner.class.getSimpleName();

    public KSSpinner(Context context) {
        super(context);
        init();
    }

    public KSSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public KSSpinner(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setOnKeyListener(mKeyListener);
    }

    /**
     * 是否需要收回下拉框标志位
     */
    private boolean isNeedRecycle = true;

    public OnKeyListener mKeyListener = new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.i(TAG, "接收到按键事件  onKey: " + keyCode);
            BaseAdapter adapter = (BaseAdapter) getAdapter();
            int size = adapter.getCount();
            if (Key.Convert.KEYCODE_XING == keyCode) {
                int pos = getSelectedItemPosition();
                if (pos < (size - 1)) {
                    pos++;
                } else {
                    pos = 0;
                }
                setSelection(pos);
                return true;
            }else if (Key.Convert.KEYCODE_JING == keyCode){
                //置反标志位，第一次点击为展开下拉框，不进入收回下拉框判断逻辑
                isNeedRecycle = !isNeedRecycle;
                //收回下拉框逻辑
                if (isNeedRecycle) {
                    onDetachedFromWindow();     //收回下拉框
                    onAttachedToWindow();       //调用onDetachedFromWindow方法后 Spinner视图会被销毁隐藏，此方法用于重新绑定显示Spinner
                }
            }
            return false;
        }
    };
}
